<!-- src/components/InstrumentForm.vue -->
<template>


    <el-dialog v-model="localVisible" width="50%" @close="handleClose">
        {{ form }}

        <template #title>
            <span style="font-weight: bold;">{{ formType === 'measurement' ? '添加测量仪表' : '添加控制仪表' }}</span>
        </template>

        <el-form :model="form" ref="formRef" :rules="rules" label-width="120px">
            <el-form-item v-if="formType === 'unknown'" label="请选择设备类型">
                <el-select v-model="form.InstrumentType" placeholder="请选择设备类型">
                    <el-option label="测量仪表" value="measurement"></el-option>
                    <el-option label="控制仪表" value="control"></el-option>
                </el-select>
            </el-form-item>

            <template v-if="form.InstrumentType === 'measurement' || formType === 'measurement'">
                <!-- 测量仪表表单内容 -->

                <el-form-item label="测量参数" prop="measurementParameter">
                    <el-select v-model="form.measurementParameter" placeholder="请选择测量参数">
                        <el-option label="温度" value="温度"></el-option>
                        <el-option label="压力" value="压力"></el-option>
                        <el-option label="流量" value="流量"></el-option>
                        <el-option label="其他" value="其他"></el-option>
                    </el-select>
                </el-form-item>
                <el-form-item v-if="form.measurementParameter === '其他'" label="请输入测量参数">
                    <el-input style="width: 150px;" v-model="form.otherMeasurementParameter"></el-input>
                </el-form-item>
                <el-form-item prop="deviceName" label="仪表名称">
                    <el-input placeholder="请输入设备的名称型号" v-model="form.deviceName" prop="deviceName"></el-input>
                </el-form-item>
                <el-form-item label="测量精度">
                    <el-input-number v-model="form.measurementAccuracy" :step="0.01" :min="0" controls-position="right"
                        placeholder="请输入精度"></el-input-number>
                </el-form-item>
                <el-form-item label="数据更新频率">
                    <el-input-number size="defalut" v-model="form.updateFrequency" :step="1" :min="0"
                        controls-position="right" placeholder="请输入频率">

                    </el-input-number><span style="margin-left: 10px;">单位: Hz</span>

                </el-form-item>

                <!-- 环境适应性 -->
                <el-form-item label="环境适应性">
                    <el-radio-group v-model="form.environmentAdaptability">
                        <el-radio label="industrial">工业级</el-radio>
                        <el-radio label="commercial">商业级</el-radio>
                    </el-radio-group>
                </el-form-item>

                <!-- 数据传输要求 -->
                <el-form-item label="数据传输要求">
                    <el-radio-group v-model="form.dataTransmissionRequirement">
                        <el-radio label="wired">有线</el-radio>
                        <el-radio label="wireless">无线</el-radio>
                    </el-radio-group>
                </el-form-item>

                <!-- 化学腐蚀性环境 -->
                <el-form-item label="化学腐蚀性环境">
                    <el-radio-group v-model="form.chemicalCorrosiveEnvironment">
                        <el-radio label="yes">是</el-radio>
                        <el-radio label="no">否</el-radio>
                    </el-radio-group>
                </el-form-item>

                <!-- 设备供电 -->
                <el-form-item label="设备供电">
                    <el-radio-group v-model="form.devicePowerSupply">
                        <el-radio label="grid">电网</el-radio>
                        <el-radio label="battery">电池</el-radio>
                    </el-radio-group>
                </el-form-item>

                <!-- 使用场所 -->
                <el-form-item label="使用场所">
                    <el-radio-group v-model="form.usageLocation">
                        <el-radio label="indoor">室内</el-radio>
                        <el-radio label="outdoor">户外</el-radio>
                    </el-radio-group>
                </el-form-item>

                <el-form-item label="其他要求">
                    <el-input type="textarea" v-model="form.otherRequirements" :rows="2"
                        placeholder="请输入您认为需要考虑的其他要求"></el-input>
                </el-form-item>
                <el-form-item label="设备说明书上传">
                    <el-upload ref="manualUpload" class="upload-demo" action="" accept=".pdf"
                        :file-list="form.fileList.manual" :limit="5" :on-exceed="handleExceedManual"
                        :on-remove="handleRemoveManual" :on-change="handleChangeManual" :auto-upload="false"
                        :multiple="true">
                        <template v-slot:trigger>
                            <el-button type="primary">上传说明书</el-button>
                        </template>
                        <template v-slot:tip>
                            <div class="el-upload__tip">最多上传 5 份文件，文件大小不超过 5MB，文件类型仅支持 PDF</div>
                        </template>
                    </el-upload>
                </el-form-item>

                <el-form-item label="设备照片上传">
                    <el-upload ref="photosUpload" class="upload-demo" action="" accept=".jpg,.jpeg,.png"
                        :file-list="form.fileList.photos" :limit="5" list-type="picture-card"
                        :on-exceed="handleExceedPhotos" :on-remove="handleRemovePhotos" :on-change="handleChangePhotos"
                        :auto-upload="false" :multiple="true">
                        <el-icon class="avatar-uploader-icon">
                            <Plus />
                        </el-icon>
                        <template v-slot:tip>
                            <div class="el-upload__tip">最多上传 5 张图片，图片大小不超过 5MB，文件类型仅支持 JPG / PNG</div>
                        </template>
                    </el-upload>
                </el-form-item>

            </template>


            <template v-if="form.InstrumentType === 'control' || formType === 'control'">
                <!-- 控制仪表表单内容 -->
                <el-form-item label="控制对象" prop="controlObject">
                    <el-input v-model="form.controlObject" placeholder="请输入您需要控制的对象设备"></el-input>
                </el-form-item>
                <el-form-item label="设备名称" prop="deviceName">
                    <el-input placeholder="请输入设备的名称型号" v-model="form.deviceName"></el-input>
                </el-form-item>
                <el-form-item label="控制精度">
                    <el-input-number v-model="form.controlAccuracy" :step="0.01" :min="0" controls-position="right"
                        placeholder="请输入精度"></el-input-number>
                </el-form-item>

                <!-- 环境适应性 -->
                <el-form-item label="环境适应性">
                    <el-radio-group v-model="form.environmentAdaptability">
                        <el-radio label="industrial">工业级</el-radio>
                        <el-radio label="commercial">商业级</el-radio>
                    </el-radio-group>
                </el-form-item>

                <!-- 数据传输要求 -->
                <el-form-item label="数据传输要求">
                    <el-radio-group v-model="form.dataTransmissionRequirement">
                        <el-radio label="wired">有线</el-radio>
                        <el-radio label="wireless">无线</el-radio>
                    </el-radio-group>
                </el-form-item>

                <!-- 化学腐蚀性环境 -->
                <el-form-item label="化学腐蚀性环境">
                    <el-radio-group v-model="form.chemicalCorrosiveEnvironment">
                        <el-radio label="yes">是</el-radio>
                        <el-radio label="no">否</el-radio>
                    </el-radio-group>
                </el-form-item>

                <!-- 设备供电 -->
                <el-form-item label="设备供电">
                    <el-radio-group v-model="form.devicePowerSupply">
                        <el-radio label="grid">电网</el-radio>
                        <el-radio label="battery">电池</el-radio>
                    </el-radio-group>
                </el-form-item>

                <!-- 使用场所 -->
                <el-form-item label="使用场所">
                    <el-radio-group v-model="form.usageLocation">
                        <el-radio label="indoor">室内</el-radio>
                        <el-radio label="outdoor">户外</el-radio>
                    </el-radio-group>
                </el-form-item>


                <el-form-item label="其他要求">
                    <el-input type="textarea" v-model="form.otherRequirements" :rows="2"
                        placeholder="请输入其他要求，如环境适应性（温度范围、湿度范围等），数据传输要求（有线、无线等）"></el-input>
                </el-form-item>
                <el-form-item label="设备说明书上传">
                    <el-upload ref="manualUpload" class="upload-demo" action="" accept=".pdf"
                        :file-list="form.fileList.manual" :limit="5" :on-exceed="handleExceedManual"
                        :on-remove="handleRemoveManual" :on-change="handleChangeManual" :auto-upload="false"
                        :multiple="true">
                        <template v-slot:trigger>
                            <el-button type="primary">上传说明书</el-button>
                        </template>
                        <template v-slot:tip>
                            <div class="el-upload__tip">最多上传 5 份文件，文件大小不超过 5MB，文件类型仅支持 PDF</div>
                        </template>
                    </el-upload>
                </el-form-item>

                <el-form-item label="设备照片上传">
                    <el-upload ref="photosUpload" class="upload-demo" action="" accept=".jpg,.jpeg,.png"
                        :file-list="form.fileList.photos" :limit="5" list-type="picture-card"
                        :on-exceed="handleExceedPhotos" :on-remove="handleRemovePhotos" :on-change="handleChangePhotos"
                        :auto-upload="false" :multiple="true">
                        <el-icon class="avatar-uploader-icon">
                            <Plus />
                        </el-icon>
                        <template v-slot:tip>
                            <div class="el-upload__tip">最多上传 5 张图片，图片大小不超过 5MB，文件类型仅支持 JPG / PNG</div>
                        </template>
                    </el-upload>
                </el-form-item>
            </template>
        </el-form>


        <template #footer>
            <el-button @click="handleClose">取消</el-button>
            <el-button type="primary" @click="handleSubmit">提交</el-button>
        </template>
    </el-dialog>
</template>

<script setup>
import { ref, watch } from 'vue';
import { ElMessage } from 'element-plus';


const props = defineProps({
    visible: Boolean,
    formType: String,
    initialData: Object
});

const emit = defineEmits(['update:visible', 'submit']);


const localVisible = ref(false);

watch(
    () => props.visible,
    (newVal) => {
        localVisible.value = newVal;
    }
);

const rules = ref({
    deviceName: [
        { required: true, message: '请输入设备名称', trigger: 'change' }
    ],
    measurementParameter: [
        { required: true, message: '请选择测量参数', trigger: 'change' }
    ],
    controlObject: [
        { required: true, message: '请输入控制对象', trigger: 'change' }
    ],
});


const form = ref({
    InstrumentType: '', // 添加 InstrumentType 字段
    measurementParameter: '',
    otherMeasurementParameter: '',
    controlObject: '',
    deviceName: '',
    measurementAccuracy: 0.01,
    controlAccuracy: 0.01,
    updateFrequency: 50,
    environmentAdaptability: '', // 环境适应性
    dataTransmissionRequirement: '', // 数据传输要求
    chemicalCorrosiveEnvironment: '', // 化学腐蚀性环境
    devicePowerSupply: '', // 设备供电
    usageLocation: '', // 使用场所
    otherRequirements: '',
    fileList: { manual: [], photos: [] },
    isUnknown: false
});


watch(() => props.visible, (newVisible) => {
    if (newVisible) {
        resetForm();
        if (props.initialData) {
            Object.assign(form.value, props.initialData);
        }
        if (props.formType !== 'unknown') {
            form.value.InstrumentType = props.formType;
            form.value.isUnknown = false;
        } else {
            form.value.isUnknown = true;
        }
    }
});

const resetForm = () => {
    form.value = {
        InstrumentType: '', // 添加 InstrumentType 字段
        measurementParameter: '',
        otherMeasurementParameter: '',
        controlObject: '',
        deviceName: '',
        measurementAccuracy: 0.01,
        controlAccuracy: 0.01,
        updateFrequency: 50,
        otherRequirements: '',
        fileList: { manual: [], photos: [] },
        isUnknown: false
    };
};


const formRef = ref(null);


const handleExceedManual = (file, fileList) => {
    form.value.fileList.manual = fileList
    ElMessage.warning('超出文件数量限制');
};

const handleExceedPhotos = (file, fileList) => {
    form.value.fileList.photos = fileList
    ElMessage.warning('超出文件数量限制');
};


const handleRemoveManual = (file, fileList) => {
    form.value.fileList.manual = fileList
};

const handleRemovePhotos = (file, fileList) => {
    form.value.fileList.photos = fileList
};
const manualUpload = ref()
const photosUpload = ref()
const handleChangeManual = (file, fileList) => {
    const isJPG = file.raw.type === 'application/pdf';
    const isLt5M = file.size / 1024 / 1024 < 5;
    if (!isJPG) {
        ElMessage.error('上传图片只能是 PDF 格式!');
        // 移除不符合条件的文件
        manualUpload.value.handleRemove(file)
        return;
    }
    if (!isLt5M) {
        ElMessage.error('上传图片大小不能超过 5MB!');
        // 如果文件大小不符合要求，清空文件列表并返回
        manualUpload.value.handleRemove(file)
        return;
    }
    form.value.fileList.manual = fileList
};

const handleChangePhotos = (file, fileList) => {
    const isJPG = file.raw.type === 'image/jpeg' || file.raw.type === 'image/png';
    const isLt5M = file.size / 1024 / 1024 < 5;
    if (!isJPG) {
        ElMessage.error('上传图片只能是 JPG 或 PNG 格式!');
        // 移除不符合条件的文件
        photosUpload.value.handleRemove(file)

        return;
    }
    if (!isLt5M) {
        ElMessage.error('上传图片大小不能超过 5MB!');
        // 如果文件大小不符合要求，清空文件列表并返回
        photosUpload.value.handleRemove(file)
        return;
    }
    form.value.fileList.photos = fileList
};


const handleClose = () => {
    localVisible.value = false;
    emit('update:visible', false);
}

const handleSubmit = () => {
    formRef.value.validate((valid) => {
        if (valid) {
            ElMessage.success('提交成功');
            emit('submit', form.value, props.formType);
            handleClose();
            // 提交逻辑
        } else {
            ElMessage.error('请检查表单填写');
            return false;
        }
    });


};

</script>
<style scoped></style>